package palmtop.com.palmtop.activity;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.beardedhen.androidbootstrap.BootstrapEditText;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import net.grandcentrix.tray.AppPreferences;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import palmtop.com.palmtop.R;
import palmtop.com.palmtop.adapter.CustomMultipleChoiceView;
import palmtop.com.palmtop.model.Task;
import palmtop.com.palmtop.model.Unit;
import palmtop.com.palmtop.model.User;
import palmtop.com.palmtop.util.Config;
import palmtop.com.palmtop.util.FuncUtil;
import palmtop.com.palmtop.util.MusicPlayer;
import palmtop.com.palmtop.util.NetUtil;
import palmtop.com.palmtop.util.ToastUtil;

public class DistributeGridActivity extends BaseActivity {

    @BindView(R.id.mtitle)
    TextView mtitle;
    @BindView(R.id.taskname)
    BootstrapEditText taskname;
    @BindView(R.id.taskaddress)
    BootstrapEditText taskaddress;
    @BindView(R.id.selectmapBtn)
    Button selectmapBtn;
    @BindView(R.id.longitude)
    BootstrapEditText longitude;
    @BindView(R.id.latitude)
    BootstrapEditText latitude;
    @BindView(R.id.taskcontent)
    BootstrapEditText taskcontent;
    @BindView(R.id.receivername)
    BootstrapEditText receivername;
    @BindView(R.id.receiveBtn)
    Button receiveBtn;
    @BindView(R.id.footBtn)
    Button footBtn;
    @BindView(R.id.zphoto1)
    ImageButton zphoto1;
    @BindView(R.id.zphoto2)
    ImageButton zphoto2;
    @BindView(R.id.zphoto3)
    ImageButton zphoto3;
    @BindView(R.id.zphoto4)
    ImageButton zphoto4;


    private ArrayList<String> urlarr;
    private String filePathstart1, filePathstart2, filePathstart3, filePathstart4;
    private File cameraFilestart1, cameraFilestart2, cameraFilestart3, cameraFilestart4;
    private String filePathstartPress1, filePathstartPress2, filePathstartPress3, filePathstartPress4;



    private ArrayList arrlist;
    Context context;
    boolean[] checkitem;
    private ArrayList<String> useridlist;
    Task task;
    String ssgrid = "";
    String gridname = "";
    String userid = "";
    String name = "";
    ArrayList<User> userlist;
    String receiverid = "";
    private PopupWindow stationSelectDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_distribute_grid, Config.toptitle, 1);
        MyApplication app = (MyApplication) getApplication();
        app.addActivityList(DistributeGridActivity.this);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        mtitle.setText("下发任务");
        footBtn.setText("下发");

        AppPreferences appPreferences = new AppPreferences(DistributeGridActivity.this);
        ssgrid = appPreferences.getString("ssgrid", "");
        gridname = appPreferences.getString("gridname", "");
        userid = appPreferences.getString("userid", "");
        name = appPreferences.getString("name", "");
        urlarr = new ArrayList<String>();
        arrlist = new ArrayList<String>();
        useridlist = new ArrayList<String>();
        context = this;
        userlist = new ArrayList<User>();
        //loadSpinner();
    }

    @OnClick(R.id.selectmapBtn)
    public void onSelectmapBtnClicked() {
        startActivityForResult(new Intent(DistributeGridActivity.this, SelectPositionActivity.class), 5);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        if(requestCode!=null){
        if (requestCode == 1) {
            mPhotoPopwindow1.dismiss();
            if (resultCode == RESULT_OK) {
                if (cameraFilestart1 != null) {
                    Bitmap bitmap = null;
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 7;//直接设置它的压缩率，表示1/2
                    filePathstartPress1 = Environment.getExternalStorageDirectory() + "/newfiles_" + System.currentTimeMillis() + ".jpg";
                    FileOutputStream fos = null;
                    try {
                        bitmap = BitmapFactory.decodeFile(filePathstart1, options);
                        fos = new FileOutputStream(filePathstartPress1);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                        fos.flush();
                        fos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if (bitmap != null) {
                        urlarr.add(filePathstartPress1);
                        zphoto1.setImageBitmap(bitmap);
                        zphoto1.requestFocus();
                        zphoto1.setScaleType(ImageView.ScaleType.FIT_XY);

                        zphoto1.setFocusable(true);
                        zphoto1.setFocusableInTouchMode(true);
                        zphoto1.requestFocus();
                        zphoto1.requestFocusFromTouch();
                        FuncUtil.clickShowBigPic(filePathstartPress1, zphoto1, DistributeGridActivity.this);
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "内存不足,请重新拍摄!", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
        }


        if (requestCode == 11) {
            mPhotoPopwindow1.dismiss();
            if (resultCode == RESULT_OK) {
                if (Build.VERSION.SDK_INT >= 19) {
                    handleImageOnKitKat1(data);
                } else {
                    handleImageBeforeKitKat1(data);
                }

                Bitmap bitmap = null;
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 7;//直接设置它的压缩率，表示1/2
                filePathstartPress1 = Environment.getExternalStorageDirectory() + "/newfiles_" + System.currentTimeMillis() + ".jpg";
                FileOutputStream fos = null;
                try {
                    bitmap = BitmapFactory.decodeFile(filePathstart1, options);
                    fos = new FileOutputStream(filePathstartPress1);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    fos.flush();
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (bitmap != null) {
                    urlarr.add(filePathstartPress1);
                    zphoto1.setImageBitmap(bitmap);
                    zphoto1.requestFocus();
                    zphoto1.setScaleType(ImageView.ScaleType.FIT_XY);

                    zphoto1.setFocusable(true);
                    zphoto1.setFocusableInTouchMode(true);
                    zphoto1.requestFocus();
                    zphoto1.requestFocusFromTouch();
                    FuncUtil.clickShowBigPic(filePathstartPress1, zphoto1, DistributeGridActivity.this);
                }
            }
        }

//=====================222===========================
        if (requestCode == 2) {
            mPhotoPopwindow2.dismiss();
            if (resultCode == RESULT_OK) {
                if (cameraFilestart2 != null) {
                    Bitmap bitmap = null;
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 7;//直接设置它的压缩率，表示1/2
                    filePathstartPress2 = Environment.getExternalStorageDirectory() + "/newfiles_" + System.currentTimeMillis() + ".jpg";
                    FileOutputStream fos = null;
                    try {
                        bitmap = BitmapFactory.decodeFile(filePathstart2, options);
                        fos = new FileOutputStream(filePathstartPress2);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                        fos.flush();
                        fos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if (bitmap != null) {
                        urlarr.add(filePathstartPress2);
                        zphoto2.setImageBitmap(bitmap);
                        zphoto2.requestFocus();
                        zphoto2.setScaleType(ImageView.ScaleType.FIT_XY);

                        zphoto2.setFocusable(true);
                        zphoto2.setFocusableInTouchMode(true);
                        zphoto2.requestFocus();
                        zphoto2.requestFocusFromTouch();
                        FuncUtil.clickShowBigPic(filePathstartPress2, zphoto2, DistributeGridActivity.this);
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "内存不足,请重新拍摄!", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
        }

        if (requestCode == 12) {
            mPhotoPopwindow2.dismiss();
            if (resultCode == RESULT_OK) {
                if (Build.VERSION.SDK_INT >= 19) {
                    handleImageOnKitKat2(data);
                } else {
                    handleImageBeforeKitKat2(data);
                }

                Bitmap bitmap = null;
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 7;//直接设置它的压缩率，表示1/2
                filePathstartPress2 = Environment.getExternalStorageDirectory() + "/newfiles_" + System.currentTimeMillis() + ".jpg";
                FileOutputStream fos = null;
                try {
                    bitmap = BitmapFactory.decodeFile(filePathstart2, options);
                    fos = new FileOutputStream(filePathstartPress2);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    fos.flush();
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (bitmap != null) {
                    urlarr.add(filePathstartPress2);
                    zphoto2.setImageBitmap(bitmap);
                    zphoto2.requestFocus();
                    zphoto2.setScaleType(ImageView.ScaleType.FIT_XY);

                    zphoto2.setFocusable(true);
                    zphoto2.setFocusableInTouchMode(true);
                    zphoto2.requestFocus();
                    zphoto2.requestFocusFromTouch();
                    FuncUtil.clickShowBigPic(filePathstartPress2, zphoto2, DistributeGridActivity.this);
                }
            }
        }
//======================================================
        if (requestCode == 3) {
            mPhotoPopwindow3.dismiss();
            if (resultCode == RESULT_OK) {
                if (cameraFilestart3 != null) {
                    Bitmap bitmap = null;
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 7;//直接设置它的压缩率，表示1/2
                    filePathstartPress3 = Environment.getExternalStorageDirectory() + "/newfiles_" + System.currentTimeMillis() + ".jpg";
                    FileOutputStream fos = null;
                    try {
                        bitmap = BitmapFactory.decodeFile(filePathstart3, options);
                        fos = new FileOutputStream(filePathstartPress3);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                        fos.flush();
                        fos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if (bitmap != null) {
                        urlarr.add(filePathstartPress3);
                        zphoto3.setImageBitmap(bitmap);
                        zphoto3.requestFocus();
                        zphoto3.setScaleType(ImageView.ScaleType.FIT_XY);

                        zphoto3.setFocusable(true);
                        zphoto3.setFocusableInTouchMode(true);
                        zphoto3.requestFocus();
                        zphoto3.requestFocusFromTouch();
                        FuncUtil.clickShowBigPic(filePathstartPress3, zphoto3, DistributeGridActivity.this);
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "内存不足,请重新拍摄!", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
        }

        if (requestCode == 13) {
            mPhotoPopwindow3.dismiss();
            if (resultCode == RESULT_OK) {
                if (Build.VERSION.SDK_INT >= 19) {
                    handleImageOnKitKat3(data);
                } else {
                    handleImageBeforeKitKat3(data);
                }

                Bitmap bitmap = null;
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 7;//直接设置它的压缩率，表示1/2
                filePathstartPress3 = Environment.getExternalStorageDirectory() + "/newfiles_" + System.currentTimeMillis() + ".jpg";
                FileOutputStream fos = null;
                try {
                    bitmap = BitmapFactory.decodeFile(filePathstart3, options);
                    fos = new FileOutputStream(filePathstartPress3);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    fos.flush();
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (bitmap != null) {
                    urlarr.add(filePathstartPress3);
                    zphoto3.setImageBitmap(bitmap);
                    zphoto3.requestFocus();
                    zphoto3.setScaleType(ImageView.ScaleType.FIT_XY);

                    zphoto3.setFocusable(true);
                    zphoto3.setFocusableInTouchMode(true);
                    zphoto3.requestFocus();
                    zphoto3.requestFocusFromTouch();
                    FuncUtil.clickShowBigPic(filePathstartPress3, zphoto3, DistributeGridActivity.this);
                }
            }
        }
//=====================================================================
        if (requestCode == 4) {
            mPhotoPopwindow4.dismiss();
            if (resultCode == RESULT_OK) {
                if (cameraFilestart4 != null) {
                    Bitmap bitmap = null;
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = 7;//直接设置它的压缩率，表示1/2
                    filePathstartPress4 = Environment.getExternalStorageDirectory() + "/newfiles_" + System.currentTimeMillis() + ".jpg";
                    FileOutputStream fos = null;
                    try {
                        bitmap = BitmapFactory.decodeFile(filePathstart4, options);
                        fos = new FileOutputStream(filePathstartPress4);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                        fos.flush();
                        fos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    if (bitmap != null) {
                        urlarr.add(filePathstartPress4);
                        zphoto4.setImageBitmap(bitmap);
                        zphoto4.requestFocus();
                        zphoto4.setScaleType(ImageView.ScaleType.FIT_XY);

                        zphoto4.setFocusable(true);
                        zphoto4.setFocusableInTouchMode(true);
                        zphoto4.requestFocus();
                        zphoto4.requestFocusFromTouch();
                        FuncUtil.clickShowBigPic(filePathstartPress4, zphoto4, DistributeGridActivity.this);
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "内存不足,请重新拍摄!", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
        }

        if (requestCode == 14) {
            mPhotoPopwindow4.dismiss();
            if (resultCode == RESULT_OK) {
                if (Build.VERSION.SDK_INT >= 19) {
                    handleImageOnKitKat4(data);
                } else {
                    handleImageBeforeKitKat4(data);
                }

                Bitmap bitmap = null;
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 7;//直接设置它的压缩率，表示1/2
                filePathstartPress4 = Environment.getExternalStorageDirectory() + "/newfiles_" + System.currentTimeMillis() + ".jpg";
                FileOutputStream fos = null;
                try {
                    bitmap = BitmapFactory.decodeFile(filePathstart4, options);
                    fos = new FileOutputStream(filePathstartPress4);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    fos.flush();
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (bitmap != null) {
                    urlarr.add(filePathstartPress4);
                    zphoto4.setImageBitmap(bitmap);
                    zphoto4.requestFocus();
                    zphoto4.setScaleType(ImageView.ScaleType.FIT_XY);

                    zphoto4.setFocusable(true);
                    zphoto4.setFocusableInTouchMode(true);
                    zphoto4.requestFocus();
                    zphoto4.requestFocusFromTouch();
                    FuncUtil.clickShowBigPic(filePathstartPress4, zphoto4, DistributeGridActivity.this);
                }
            }
        }

            if (requestCode == 5) {
                if(data!=null){
                    String address = data.getExtras().getString("address");
                    Double  latitude1 = data.getExtras().getDouble("latitude");
                    Double longitude1 = data.getExtras().getDouble("longitude");
                    taskaddress.setText(address);
                    if(latitude1==0.0){
                        latitude.setText("");
                    }else{
                        latitude.setText(String.valueOf(latitude1));
                    }
                    if(longitude1==0.0){
                        longitude.setText("");
                    }else{
                        longitude.setText(String.valueOf(longitude1));
                    }
                }

            }
//        }

    }


    @OnClick(R.id.receiveBtn)
    public void onReceiveBtnClicked1() {

        RequestParams params = new RequestParams(Config.SERVER_URL + "sys/loginapi/getListBySsgrid");
        params.addBodyParameter("ssgrid", ssgrid);
        NetUtil.postData(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                Type listType = new TypeToken<ArrayList<User>>() {
                }.getType();
                ArrayList<User> list = gson.fromJson(result, listType);
                userlist = gson.fromJson(result, listType);
                if (list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        arrlist.add(list.get(i).getName());
                    }
                }

                ArrayList<String> usernameList = new ArrayList<String>();

                if (list.size() > 0) {
                    for (User user : list) {
                        usernameList.add(user.getName());
                    }
                }
                String[] arrs = new String[usernameList.size()];
                usernameList.toArray(arrs);
                showMutiChoiceDialog(arrs, receivername);

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });




    }
    private void showMutiChoiceDialog(final String[] stationsMean, final BootstrapEditText textView){
        if(stationSelectDialog == null){
            LayoutInflater inflater = LayoutInflater.from(this);
            View view = inflater.inflate(R.layout.dialog_multiplechoice, null);
            CustomMultipleChoiceView mutipleChoiceView = (CustomMultipleChoiceView) view.findViewById(R.id.CustomMultipleChoiceView);
            mutipleChoiceView.setData(stationsMean, null);
//            mutipleChoiceView.selectAll();
            mutipleChoiceView.setTitle("选择接收人");
            stationSelectDialog = new PopupWindow(view, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
            mutipleChoiceView.setOnSelectedListener(new CustomMultipleChoiceView.onSelectedListener() {
                @Override
                public void onSelected(SparseBooleanArray sparseBooleanArray) {
                    stationSelectDialog.dismiss();
                    StringBuilder sb = new StringBuilder();
//                    unitidlist.clear();
                    receiverid = "";
                    for(int i=0; i<sparseBooleanArray.size(); i++){
                        if(sparseBooleanArray.get(i)){
                            sb.append(stationsMean[i] + ",");
//                            addUnitid(stationsMean[i]);
                            for (int j = 0; j < userlist.size(); j++) {
                                if (stationsMean[i].equals(userlist.get(j).getName())) {
                                    receiverid += userlist.get(i).getId() + ",";
                                    continue;
                                }
                            }
                        }

                    }
                    if(sb.length() > 0)
                        sb.deleteCharAt(sb.length()-1);
                    textView.setText(sb.toString());
                }
            });
        }
        stationSelectDialog.showAtLocation(getCurrentFocus(), Gravity.CENTER, 0, 0);
    }

    //@OnClick(R.id.receiveBtn)
    public void onReceiveBtnClicked() {
        RequestParams params = new RequestParams(Config.SERVER_URL + "sys/loginapi/getListBySsgrid");
        params.addBodyParameter("ssgrid", ssgrid);
        NetUtil.postData(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                Type listType = new TypeToken<ArrayList<User>>() {
                }.getType();
                ArrayList<User> list = gson.fromJson(result, listType);
                userlist = gson.fromJson(result, listType);
                if (list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        arrlist.add(list.get(i).getName());
                    }
                }

                ArrayList<String> usernameList = new ArrayList<String>();

                if (list.size() > 0) {
                    for (User user : list) {
                        usernameList.add(user.getName());
                    }
                }
                final String[] userdata = new String[usernameList.size()];
                checkitem = new boolean[list.size()];
                for (int a = 0; a < usernameList.size(); a++) {
                    userdata[a] = usernameList.get(a);
                    checkitem[a] = false;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setMultiChoiceItems(userdata, checkitem, new
                        DialogInterface.OnMultiChoiceClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                                checkitem[which] = isChecked;
                            }
                        });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String text = "";
                        receiverid = "";
                        for (int a = 0; a < userdata.length; a++) {
                            if (checkitem[a]) {
                                text += userdata[a] + ",";
                                for (int i = 0; i < userlist.size(); i++) {
                                    if (userdata[a].equals(userlist.get(i).getName())) {
                                        receiverid += userlist.get(i).getId() + ",";

                                    }
                                }
                                //addUserid(userdata[a]);
                            }
                        }
                        receivername.setText(text);
                    }
                });
                builder.show();

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
    }

    private void addUserid(String username) {
        RequestParams params = new RequestParams(Config.SERVER_URL + "sys/loginapi/getUserByName");
        params.addBodyParameter("name", username);
        NetUtil.postData(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                Type listType = new TypeToken<ArrayList<User>>() {
                }.getType();
                ArrayList<User> list = gson.fromJson(result, listType);
                if (list.size() > 0) {
                    useridlist.add(String.valueOf(list.get(0).getId()));
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });


    }

    @OnClick(R.id.footBtn)
    public void onFootBtnClicked() {
        if(TextUtils.isEmpty(taskname.getText())){
            ToastUtil.show(this,"任务名称不能为空");
            return;
        }
        if(TextUtils.isEmpty(taskaddress.getText())){
            ToastUtil.show(this,"任务地点不能为空");
            return;
        }
        if(TextUtils.isEmpty(taskcontent.getText())){
            ToastUtil.show(this,"具体内容不能为空");
            return;
        }
        if(TextUtils.isEmpty(receivername.getText())){
            ToastUtil.show(this,"接收人不能为空");
            return;
        }
        RequestParams params = new RequestParams(Config.SERVER_URL + "taskgridapp/save");
        params.addBodyParameter("orataskid", "0");
        params.addBodyParameter("taskname", String.valueOf(taskname.getText()));//任务内容
        params.addBodyParameter("taskaddress", String.valueOf(taskaddress.getText()));//任务地点
        params.addBodyParameter("taskcontent", String.valueOf(taskcontent.getText()));//具体内容
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String date = sDateFormat.format(new Date());
        params.addBodyParameter("adddate", date);// 添加时间
        params.addBodyParameter("longitude", String.valueOf(longitude.getText()));
        params.addBodyParameter("latitude", String.valueOf(latitude.getText()));
        params.addBodyParameter("status", "2");
        params.addBodyParameter("receivername", String.valueOf(receivername.getText()));
        params.addBodyParameter("unitid", ssgrid);
        params.addBodyParameter("unitname", gridname);
        params.addBodyParameter("addusername", name);
        params.addBodyParameter("adduserid", userid);
        params.addBodyParameter("receiverid", receiverid);

        if (urlarr != null && urlarr.size() > 0) {
            if (urlarr.get(0) != null && !urlarr.get(0).equals("")) {
                params.addBodyParameter("phone1", new File(urlarr.get(0)));
            }
        }
        if (urlarr != null && urlarr.size() > 1) {
            if (urlarr.get(1) != null && !urlarr.get(1).equals("")) {
                params.addBodyParameter("phone2", new File(urlarr.get(1)));
            }
        }
        if (urlarr != null && urlarr.size() > 2) {
            if (urlarr.get(2) != null && !urlarr.get(2).equals("")) {
                params.addBodyParameter("phone3", new File(urlarr.get(2)));
            }
        }
        if (urlarr != null && urlarr.size() > 3) {
            if (urlarr.get(3) != null && !urlarr.get(3).equals("")) {
                params.addBodyParameter("phone4", new File(urlarr.get(3)));
            }
        }

        NetUtil.postData(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                if (result.equals("success")) {
                    ToastUtil.show(DistributeGridActivity.this, "提交成功");
                    finish();

                } else {
                    ToastUtil.show(DistributeGridActivity.this, "提交失败");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });
    }

    //==================================================================================================
    public PhotoPopwindow mPhotoPopwindow1;
    public PhotoPopwindow mPhotoPopwindow2;
    public PhotoPopwindow mPhotoPopwindow3;
    public PhotoPopwindow mPhotoPopwindow4;
    private Uri imageUri;//原图保存地址

    private Handler mHandler1 = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 110:
                    takephoto1();
                    break;
                case 111:
                    selectFromAlbum1();
                    break;
                default:
                    break;
            }
        }
    };

    private Handler mHandler2 = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 110:
                    takephoto2();
                    break;
                case 111:
                    selectFromAlbum2();
                    break;
                default:
                    break;
            }
        }
    };

    private Handler mHandler3 = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 110:
                    takephoto3();
                    break;
                case 111:
                    selectFromAlbum3();
                    break;
                default:
                    break;
            }
        }
    };

    private Handler mHandler4 = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 110:
                    takephoto4();
                    break;
                case 111:
                    selectFromAlbum4();
                    break;
                default:
                    break;
            }
        }
    };
    @OnClick(R.id.zphoto1)
    public void onZphoto1Clicked() {
        mPhotoPopwindow1 = new PhotoPopwindow(DistributeGridActivity.this, mHandler1,this.getWindowManager());
        mPhotoPopwindow1.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        mPhotoPopwindow1.showAtLocation(findViewById(R.id.footBtn),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    public void takephoto1(){
        filePathstart1 = Environment.getExternalStorageDirectory() + "/files_" + System.currentTimeMillis() + ".png";
        cameraFilestart1 = new File(filePathstart1);
        Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        in.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFilestart1));
        startActivityForResult(in, 1);
    }
    /**
     * 从相册选择
     */
    private void selectFromAlbum1() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, 11);
    }

    @TargetApi(19)
    private void handleImageOnKitKat1(Intent data) {
        filePathstart1 = null;
        imageUri = data.getData();
        if (DocumentsContract.isDocumentUri(this, imageUri)) {
            //如果是document类型的uri,则通过document id处理
            String docId = DocumentsContract.getDocumentId(imageUri);
            if ("com.android.providers.media.documents".equals(imageUri.getAuthority())) {
                String id = docId.split(":")[1];//解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                filePathstart1 = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.downloads.documents".equals(imageUri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                filePathstart1 = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            //如果是content类型的Uri，则使用普通方式处理
            filePathstart1 = getImagePath(imageUri, null);
        } else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            //如果是file类型的Uri,直接获取图片路径即可
            filePathstart1 = imageUri.getPath();
            cameraFilestart1 = new File(filePathstart1);
        }
    }

    private void handleImageBeforeKitKat1(Intent intent) {
        imageUri = intent.getData();
        filePathstart1 = getImagePath(imageUri, null);
        cameraFilestart1 = new File(filePathstart1);
    }





    private String getImagePath(Uri uri, String selection) {
        String path = null;
        //通过Uri和selection老获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }




    //=================================================================
    @OnClick(R.id.zphoto2)
    public void onZphoto2Clicked() {
        mPhotoPopwindow2 = new PhotoPopwindow(DistributeGridActivity.this, mHandler2,this.getWindowManager());
        mPhotoPopwindow2.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        mPhotoPopwindow2.showAtLocation(findViewById(R.id.footBtn),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    public void takephoto2(){
        filePathstart2 = Environment.getExternalStorageDirectory() + "/files_" + System.currentTimeMillis() + ".png";
        cameraFilestart2 = new File(filePathstart2);
        Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        in.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFilestart2));
        startActivityForResult(in, 2);
    }
    /**
     * 从相册选择
     */
    private void selectFromAlbum2() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, 12);
    }

    @TargetApi(19)
    private void handleImageOnKitKat2(Intent data) {
        filePathstart2 = null;
        imageUri = data.getData();
        if (DocumentsContract.isDocumentUri(this, imageUri)) {
            //如果是document类型的uri,则通过document id处理
            String docId = DocumentsContract.getDocumentId(imageUri);
            if ("com.android.providers.media.documents".equals(imageUri.getAuthority())) {
                String id = docId.split(":")[1];//解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                filePathstart2 = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.downloads.documents".equals(imageUri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                filePathstart2 = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            //如果是content类型的Uri，则使用普通方式处理
            filePathstart2 = getImagePath(imageUri, null);
        } else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            //如果是file类型的Uri,直接获取图片路径即可
            filePathstart2 = imageUri.getPath();
            cameraFilestart2 = new File(filePathstart2);
        }
    }

    private void handleImageBeforeKitKat2(Intent intent) {
        imageUri = intent.getData();
        filePathstart2 = getImagePath(imageUri, null);
        cameraFilestart2 = new File(filePathstart2);
    }
    //===================================================================
    @OnClick(R.id.zphoto3)
    public void onZphoto3Clicked() {
        mPhotoPopwindow3 = new PhotoPopwindow(DistributeGridActivity.this, mHandler3,this.getWindowManager());
        mPhotoPopwindow3.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        mPhotoPopwindow3.showAtLocation(findViewById(R.id.footBtn),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    public void takephoto3(){
        filePathstart3 = Environment.getExternalStorageDirectory() + "/files_" + System.currentTimeMillis() + ".png";
        cameraFilestart3 = new File(filePathstart3);
        Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        in.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFilestart3));
        startActivityForResult(in, 3);
    }
    /**
     * 从相册选择
     */
    private void selectFromAlbum3() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, 13);
    }

    @TargetApi(19)
    private void handleImageOnKitKat3(Intent data) {
        filePathstart3 = null;
        imageUri = data.getData();
        if (DocumentsContract.isDocumentUri(this, imageUri)) {
            //如果是document类型的uri,则通过document id处理
            String docId = DocumentsContract.getDocumentId(imageUri);
            if ("com.android.providers.media.documents".equals(imageUri.getAuthority())) {
                String id = docId.split(":")[1];//解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                filePathstart3 = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.downloads.documents".equals(imageUri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                filePathstart3 = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            //如果是content类型的Uri，则使用普通方式处理
            filePathstart3 = getImagePath(imageUri, null);
        } else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            //如果是file类型的Uri,直接获取图片路径即可
            filePathstart3 = imageUri.getPath();
            cameraFilestart3 = new File(filePathstart3);
        }
    }

    private void handleImageBeforeKitKat3(Intent intent) {
        imageUri = intent.getData();
        filePathstart3 = getImagePath(imageUri, null);
        cameraFilestart3 = new File(filePathstart3);
    }
    //======================================================================
    @OnClick(R.id.zphoto4)
    public void onZphoto4Clicked() {
        mPhotoPopwindow4 = new PhotoPopwindow(DistributeGridActivity.this, mHandler4,this.getWindowManager());
        mPhotoPopwindow4.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        mPhotoPopwindow4.showAtLocation(findViewById(R.id.footBtn),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    public void takephoto4(){
        filePathstart4 = Environment.getExternalStorageDirectory() + "/files_" + System.currentTimeMillis() + ".png";
        cameraFilestart4 = new File(filePathstart4);
        Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        in.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFilestart4));
        startActivityForResult(in, 3);
    }
    /**
     * 从相册选择
     */
    private void selectFromAlbum4() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, 14);
    }

    @TargetApi(19)
    private void handleImageOnKitKat4(Intent data) {
        filePathstart4 = null;
        imageUri = data.getData();
        if (DocumentsContract.isDocumentUri(this, imageUri)) {
            //如果是document类型的uri,则通过document id处理
            String docId = DocumentsContract.getDocumentId(imageUri);
            if ("com.android.providers.media.documents".equals(imageUri.getAuthority())) {
                String id = docId.split(":")[1];//解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                filePathstart4 = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.downloads.documents".equals(imageUri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                filePathstart4 = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            //如果是content类型的Uri，则使用普通方式处理
            filePathstart4 = getImagePath(imageUri, null);
        } else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            //如果是file类型的Uri,直接获取图片路径即可
            filePathstart4 = imageUri.getPath();
            cameraFilestart4 = new File(filePathstart4);
        }
    }

    private void handleImageBeforeKitKat4(Intent intent) {
        imageUri = intent.getData();
        filePathstart4 = getImagePath(imageUri, null);
        cameraFilestart4 = new File(filePathstart4);
    }


}
